package com.atguigu.spzx.manager.task;

import cn.hutool.core.date.DateUtil;
import com.atguigu.spzx.manager.mapper.OrderInfoMapper;
import com.atguigu.spzx.manager.mapper.OrderStatisticsMapper;
import com.atguigu.spzx.model.entity.base.BaseEntity;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderStatistics;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author：tzl
 * @Date：2024/2/1 16:04
 * @description: 测试定时任务
 */
@Component
@Slf4j
public class OrderStatisticsTask {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    /**
     * 定时任务：每天2点会将昨日的成交金额进行统计并加入统计表中
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void orderTotalAmountStatistics() {
        // 查出今天和昨天的日期
        String startTime = DateUtil.offsetDay(new Date(), -1).toString(new SimpleDateFormat("yyyy-MM-dd"));
        String endTime = DateUtil.format(new Date(), "yyyy-MM-dd");

        // 查出昨天的所有数据
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>()
                .ge(BaseEntity::getCreateTime, startTime)
                .le(BaseEntity::getCreateTime, endTime));
        BigDecimal sum = orderInfoList.stream().map(OrderInfo::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        OrderStatistics orderStatistics = new OrderStatistics();
        orderStatistics.setOrderDate(DateUtil.offsetDay(new Date(), -1));
        orderStatistics.setTotalAmount(sum);
        orderStatistics.setTotalNum(orderInfoList.size());
        orderStatisticsMapper.insert(orderStatistics);
    }
}
